<?php
/**
 * [WeEngine System] Copyright (c) 2014 WE7.CC
 * WeEngine is NOT a free software, it under the license terms, visited http://www.we7.cc/ for more details.
 */
defined('IN_IA') or exit('Access Denied');

load()->model('phoneapp');
load()->classs('uploadedfile');

$dos = array('front_download', 'getpackage');
$do = in_array($do, $dos) ? $do : 'front_download';
$version_id = intval($_GPC['version_id']);


$is_module_wxapp = false;
if (!empty($version_id)) {
	$version_info = phoneapp_version($version_id);
	$module = !empty($version_info['modules']) ? current($version_info['modules']) : array();
}

if ('front_download' == $do) {
	$appurl = $_W['siteroot'] . '/app/index.php';
	$type = empty($_GPC['type']) ? 'apk' : safe_gpc_string($_GPC['type']);
	$account_info = phoneapp_version($version_id);
	$siteurl = $_W['siteroot'] . 'app/index.php';
	if (!empty($account_info['appdomain'])) {
		$siteurl = $account_info['appdomain'];
	}
	$siteinfo = array(
		'name' => empty($account_info['name']) ? '' : $account_info['name'],
		'm' => !empty($account_info['modules'][0]) ? $account_info['modules'][0]['name'] : '',
		'uniacid' => $account_info['uniacid'],
		'acid' => empty($account_info['acid']) ? 0 : $account_info['acid'],
		'version' => $account_info['version'],
		'siteroot' => $siteurl,
	);
	template('phoneapp/front-download');
}

if ('getpackage' == $do) {
	if (empty($version_id)) {
		itoast('参数错误！', '', '');
	}
	$account_info = phoneapp_version($version_id);
	if (empty($account_info)) {
		itoast('版本不存在！', referer(), 'error');
	}
	if (0 == count($account_info['modules'])) {
		itoast('请先配置模块');
	}
	if (!is_dir(ATTACHMENT_ROOT . '/siteinfo')) {
		mkdir(ATTACHMENT_ROOT . '/siteinfo');
	}
	$module = current($account_info['modules']);
	$module_info = pdo_get('modules', array('name' => $module['name']));
	$type = 'apk' == safe_gpc_string($_GPC['type']) ? 'android' : 'ios';
	$dir_name = $module['name'] . '_' . $type;
	$zip = new ZipArchive();
	if (!is_file(IA_ROOT . '/addons/' . $module['name'] . '/' . $dir_name . '/' . $module_info['version'])) {
		rmdirs(IA_ROOT . '/addons/' . $module['name'] . '/' . $dir_name);
		$request_cloud_data = array(
			'module' => array(
				'name' => $module['name'],
				'version' => $module['version'],
			),
			'support' => $type,
			'filename' => 'package.zip'
		);
		$cloud_package = cloud_miniapp_get_package($request_cloud_data);
		if (is_error($cloud_package)) {
			itoast($cloud_package['message']);
		}
		$package = $module['name'] . '_' . $type . '_' . $_W['uniacid'] . time() . '.zip';
		$download = file_put_contents(ATTACHMENT_ROOT . '/siteinfo/' . $package, file_get_contents($cloud_package['url']));
		@chmod(ATTACHMENT_ROOT . '/siteinfo/' . $package, 0755);
		if (empty($download)) {
			itoast('文件下载失败！');
		}
		if ($zip->open(ATTACHMENT_ROOT . '/siteinfo/' . $package)) {
			$unzip = $zip->extractTo(ATTACHMENT_ROOT . '/siteinfo');
			$zip->close();
			if (empty($unzip)) {
				itoast('文件解压失败！');
			}
		} else {
			itoast('文件解压失败！');
		}
		if (!is_dir(ATTACHMENT_ROOT . '/siteinfo' . $module['name'])) {
			mkdir(ATTACHMENT_ROOT . '/siteinfo/' . $module['name']);
			$suffix = 'android' == $type ? '.apk' : '.ipa';
			@chmod(ATTACHMENT_ROOT . '/siteinfo/' . $module['name'] . $suffix, 0755);
			file_move(ATTACHMENT_ROOT . '/siteinfo/' . $module['name'] . $suffix, ATTACHMENT_ROOT . '/siteinfo/' . $module['name'] . '/' . $module['name'] . $suffix);
		}
		rename(ATTACHMENT_ROOT . '/siteinfo/' . $module['name'], ATTACHMENT_ROOT . '/siteinfo/' . $dir_name);
		file_copy(ATTACHMENT_ROOT . '/siteinfo/' . $dir_name, IA_ROOT . '/addons/' . $module['name'] . '/' . $dir_name, array());
		file_put_contents(IA_ROOT . '/addons/' . $module['name'] . '/' . $dir_name . '/' . $module['version'], '');
		@unlink(ATTACHMENT_ROOT . '/siteinfo/' . $package);
		rmdirs(ATTACHMENT_ROOT . '/siteinfo/' . $dir_name);
	}

	$module_root = IA_ROOT . '/addons/' . $module['name'] . '/';
	$uniacid_zip_name = $module['name'] . '_' . $type . '_' . $_W['uniacid'] . md5(time()) . '.zip';
	if ($zip->open($module_root . $uniacid_zip_name, ZipArchive::CREATE) === true) {
		addFileToZip($module_root . $dir_name, $zip, $module_root);
		$zip->close();
	}
	$copy_result = copy($module_root . $uniacid_zip_name, ATTACHMENT_ROOT . '/siteinfo/' . $uniacid_zip_name);
	if (!$copy_result) {
		itoast('APP包预处理打包失败，请将权限设置成755后再试！');
	} else {
		@unlink($module_root . $uniacid_zip_name);
	}
	if ($zip->open(ATTACHMENT_ROOT . '/siteinfo/' . $uniacid_zip_name) === true) {
		$zip->deleteName($dir_name . '/' . $module['version']);
		$zip->close();
	}

	header('Content-Type: application/octet-stream');
	header('Content-Disposition:attachment;filename=' . $uniacid_zip_name);
	$fp = fopen(ATTACHMENT_ROOT . '/siteinfo/' . $uniacid_zip_name, 'r+');
	$buffer = 1024;
	while (!feof($fp)) {
		$file_data = fread($fp, $buffer);
		echo $file_data;
	}
	fclose($fp);
}

function addFileToZip($path, $zip, $root_path) {
	$handler = opendir($path);
	while (($filename = readdir($handler)) !== false) {
		if ($filename != "." && $filename != "..") {
			if (is_dir($path . "/" . $filename)) {
				addFileToZip($path . "/" . $filename, $zip, $root_path);
			} else {
				$zip->addFile($path . "/" . $filename, substr($path . "/" . $filename, strlen($root_path)));
			}
		}
	}
	@closedir($handler);
	return true;
}
